package com.dashan.servlets;

import static com.dashan.Constants.SESSIONID;
import static com.dashan.Constants.USERNAME;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.dashan.backend.AuthenticationManager;

public class LoginFilter implements Filter {
    private static boolean testAuthenticate = true;
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        if (request instanceof HttpServletRequest) {
            HttpServletRequest req = ((HttpServletRequest) request);
            if (req.getMethod().compareTo("POST") == 0) {
                canAccess(req);
            }
        }
        chain.doFilter(request, response);
    }

    private void canAccess(HttpServletRequest req) throws ServletException {
        String sessionId = req.getParameter(SESSIONID);
        String userName = req.getParameter(USERNAME);
        if (sessionId == null || userName == null) {
            throw new ServletException(
                    "Access is denied, please include a session id.");
        }

        boolean authenticated = false;
        long sessionIdValue = Long.parseLong(sessionId);
        if (testAuthenticate) {
            authenticated = (sessionIdValue == 0);
        }

        authenticated |= AuthenticationManager.getAuthentication(
                userName, sessionIdValue);

        if (authenticated) {
            return;
        } else {
            throw new ServletException(
                    "Access is denied, please require a session id.");
        }
    }

    public synchronized void destroy() {

    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        // TODO Auto-generated method stub

    }
}
